local skill = fk.CreateSkill {
  name = "3s__zhixin",
}

Fk:loadTranslationTable{
  ["3s__zhixin"] = "治心",
  [":3s__zhixin"] = "你于回合内首次使用一种花色的牌结算后，可保留你本回合使用牌数张手牌并重铸其余手牌。若你保留的牌均为红桃牌，你可展示之并结束本回合。",
  ["@zhixin-inhand"] = "治心",
  ["$3s__zhixin1"] = "心若安定，万物皆明。",
  ["$3s__zhixin2"] = "禅意自在心中，何须外求？",
  ["#3s__zhixin-select"] = "治心：请保留 %arg 张手牌",
  ["#3s__zhixin-end"] = "治心：是否结束本回合？",
}

skill:addEffect(fk.CardUseFinished, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(skill.name) and not player:isKongcheng() and
    player.room.current and player.room.current == player then
      local room = player.room
      -- 计算本回合已使用同花色牌的数量，使用getEventsOfScope方法
      local use_events = room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e)
        local use = e.data
        return use.from == player and use.card and use.card.suit == data.card.suit
      end, Player.HistoryTurn)   
      return #use_events == 1
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    -- 获取本回合使用的牌数
    local total_used_events = room.logic:getEventsOfScope(GameEvent.UseCard, 999, function(e)
      return e.data.from == player
    end, Player.HistoryTurn)
    -- 保留手牌并重铸其余
    if not player:isKongcheng() then
      local selected = room:askToCards(player, {
        min_num = #total_used_events,
        max_num = #total_used_events,
        include_equip = false,
        skill_name = skill.name,
        pattern = ".",
        cancelable = true,
        prompt = "#3s__zhixin-select:::" .. #total_used_events
      })
      if #selected > 0 then
        -- 重铸其余手牌
        local to_recast = table.filter(player:getCardIds("h"), function(id)
          return not table.contains(selected, id)
        end)
        if #to_recast > 0 then
          room:recastCard(to_recast, player, skill.name)
        end
        -- 检查保留的牌是否全为红桃
        for _, id in ipairs(selected) do
          room:addCardMark(Fk:getCardById(id), "@zhixin-inhand")
        end
        if table.every(selected, function(id) return Fk:getCardById(id).suit == Card.Heart end) and
        room:askToSkillInvoke(player, { skill_name = skill.name, prompt = "#3s__zhixin-end" }) then
          -- 展示手牌
          player:showCards(selected)
          room:addPlayerMark(player, "3s__zhixin_end")
          room:endTurn()
        end
      end
    end
  end,
})

-- 回合结束时重置结束回合标记
skill:addEffect(fk.TurnStart, {
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(skill.name) and player:getMark("3s__zhixin_end") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "3s__zhixin_end", 0)
  end,
})

return skill